<template>
	<div>
		<a-modal
			:open="modalOpen"
			:width="
				props.modelInfo && props.modelInfo.width ?
					props.modelInfo.width
				:	'900px'
			"
			:title="
				props.modelInfo && props.modelInfo.title ?
					props.modelInfo.title
				:	'Basic Modal'
			"
			@ok="handleOk"
			okText="保存"
			:confirmLoading="modelConfig.confirmLoading"
			:destroyOnClose="modelConfig.destroyOnClose"
			@cancel="handleCancel"
		>
			<template #footer>
				<a-button key="back" @click="handleCancel">取消</a-button>
				<a-button
					key="submit"
					type="primary"
					:loading="loading"
					@click="handleOk"
					>保存</a-button
				>
			</template>
			<a-form
				ref="formRef"
				name="DatingInfoForm"
				class="ant-advanced-search-form"
				:model="formState"
				@finish="onFinish"
				@finishFailed="onFinishFailed"
				:rules="rulesRef"
			>
				<a-row :gutter="24">
					<a-col :span="24">
						<a-form-item
							:name="labelMap['datingTheme'].name"
							:label="labelMap['datingTheme'].label"
						>
							<a-input
								v-model:value="formState.datingTheme"
								:placeholder="'请填写' + labelMap['datingTheme'].label"
							></a-input>
						</a-form-item>
					</a-col>
				</a-row>
				<a-row :gutter="24">
					<a-col :span="24">
						<a-form-item
							:name="labelMap['content'].name"
							:label="labelMap['content'].label"
						>
							<a-textarea
								v-model:value="formState.content"
								:placeholder="'请填写' + labelMap['content'].label"
							></a-textarea>
						</a-form-item>
					</a-col>
				</a-row>
				<a-row :gutter="24">
					<a-col :span="24">
						<a-form-item
							:name="labelMap['timeInfo'].name"
							:label="labelMap['timeInfo'].label"
						>
							<a-range-picker v-model:value="formState.timeInfo" show-time />
						</a-form-item>
					</a-col>
				</a-row>
				<a-row :gutter="24">
					<a-col :span="12">
						<a-form-item
							:name="labelMap['datingType'].name"
							:label="labelMap['datingType'].label"
						>
							<a-select
								style="width: 90%; margin-left: 8px"
								ref="select"
								v-model:value="formState.datingType"
								:placeholder="'请选择' + labelMap['datingType'].label"
								:field-names="{ label: 'typeName', value: 'typeCode' }"
								:options="datingTypeList"
								:allowClear="true"
							>
							</a-select>
						</a-form-item>
					</a-col>
				</a-row>
				<a-row :gutter="24">
					<a-col :span="12">
						<a-form-item
							:name="labelMap['topFlag'].name"
							:label="labelMap['topFlag'].label"
						>
							<a-select
								style="width: 90%; margin-left: 8px"
								ref="select"
								v-model:value="formState.topFlag"
								:placeholder="'请选择' + labelMap['topFlag'].label"
								:options="topFlagList"
								:allowClear="true"
							>
							</a-select>
						</a-form-item>
					</a-col>
				</a-row>
				<a-row :gutter="24">
					<a-col :span="12">
						<a-form-item
							:name="labelMap['imageIds'].name"
							:label="labelMap['imageIds'].label"
						>
							<MyUploadList
								:fromSystem="'common'"
								:fileInfo="fileInfo"
								@customImageRequest="customImageRequest"
							>
							</MyUploadList>
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item
							:name="labelMap['userId'].name"
							:label="labelMap['userId'].label"
						>
							<a-select
								v-model:value="formState.userId"
								:placeholder="'请选择' + labelMap['userId'].label"
								:options="userList"
								:filter-option="filterOption"
								:field-names="{ value: 'id', label: 'code' }"
								show-search
								allow-clear
								:disabled="props?.modelInfo?.id != null"
							>
							</a-select>
						</a-form-item>
					</a-col>
				</a-row>
				<a-row :gutter="24">
					<a-col :span="12">
						<a-form-item
							:name="labelMap['location'].name"
							:label="labelMap['location'].label"
						>
							<a-cascader
								v-model:value="formState.location"
								:options="locationTree"
								:placeholder="'请选择' + labelMap['location'].label"
								:load-data="loadData"
								:fieldNames="{
									label: 'name',
									value: 'id',
									children: 'children',
								}"
								change-on-select
								@blur="handleChange"
							/>
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item
							:name="labelMap['payMoney'].name"
							:label="labelMap['payMoney'].label"
						>
							<a-input
								v-model:value="formState.payMoney"
								:placeholder="'请填写' + labelMap['payMoney'].label"
							></a-input>
						</a-form-item>
					</a-col>
				</a-row>
			</a-form>
		</a-modal>
	</div>
</template>
<script setup lang="ts">
import { DatingInfoDetail, labelMap, rulesRef, topFlagList } from './datingInfoDetailTs';
import { addOrEditDatingInfo, getDatingInfoDetail } from '@/api/datingInfo/datingInfo/datingInfoTs';
import { FormInstance, message } from 'ant-design-vue';
import { dictInfo } from '@/views/commonInfo/dictInfo/dictInfoListTs';
import { getDictList } from '@/api/commonInfo/dictInfo/dictInfoTs';
import { ModelInfo } from '../datingInfoListTs';
import { getLocationTree } from '@/api/eventInfo/eventInfo/eventInfoTs';
// import { reduceMoneyInfo } from '@/api/userBalanceInfo/index';
import { getUserInfoList } from '@/api/userInfo/userInfo/userInfoTs';
import { filterOption } from '@/utils/common';
import dayjs from 'dayjs';

interface Props {
	open?: boolean;
	modelInfo?: ModelInfo;
}

const props = defineProps<Props>();

let fileInfo = ref<any[]>([]);

let loading = ref<boolean>(false);

const locationTree = ref<any[]>([]);

const formRef = ref<FormInstance>();

const userList = ref<any>([]);

const modalOpen = ref<boolean>(false);

const modelConfig = {
	confirmLoading: true,
	destroyOnClose: true,
};

let formState = ref<DatingInfoDetail>({});

const firstChange = ref<boolean>(true);

let datingTypeList = ref<dictInfo[]>([]);

// 查询约会类型列表
const getDictInfoList = () => {
	getDictList('dateType').then((res) => {
		if (res.code == '200') {
			datingTypeList.value = res.data.filter(
				(item: { belongTo: string }) => item.belongTo == 'dateType',
			);
		} else {
			message.error((res && res.message) || '查询列表失败！');
		}
	});
};

// 查询地区树
const getLocationTreeInfo = async (parentId: number): Promise<any> => {
	const { data, code, message } = await getLocationTree({ parentId }).catch(
		(error: any) => {
			message.error(error?.message || '查询失败！');
		},
	);
	if (code == '200') {
		return data;
	} else {
		message.error(message || '查询失败！');
		return null;
	}
};

// 加载地区树
const loadData = async (selectedOptions: any[]) => {
	const targetOption = selectedOptions[selectedOptions.length - 1];
	targetOption.loading = true;
	targetOption.children = await getLocationTreeInfo(targetOption.id);
	if (targetOption.children.length == 0) {
		return;
	}
	targetOption.children.forEach((item: any) => {
		if (targetOption.level == 1) {
			item.isLeaf = false;
			item.level = 2;
		} else {
			item.isLeaf = true;
			item.level = 3;
		}
	});
};

// 地区树选择变化
const handleChange = (value: any) => {
	if (formState.value?.location?.length == 3) {
		firstChange.value = false;
		return;
	}
	firstChange.value = false;
	formState.value.location = [];
};

const handleOk = (): void => {
	loading.value = true;
	if (formRef.value) {
		formRef.value
			.validateFields()
			.then(() => saveDatingInfoManager())
			.catch(() => {
				loading.value = false;
			});
	}
};

const handleCancel = (): void => {
	emit('handleCancel', false);
};

//保存约会表信息
const saveDatingInfoManager = async (): Promise<void> => {
	let method = '';
	if (formState.value.id) {
		method = 'put';
	} else {
		method = 'post';
	}
	let params = {
		id: formState.value.id,
		datingType: formState.value.datingType,
		datingTheme: formState.value.datingTheme,
		startTime:
			formState.value.timeInfo ?
				dayjs(formState.value.timeInfo[0]).format('YYYY-MM-DD HH:mm:ss')
			:	null,
		endTime:
			formState.value.timeInfo ?
				dayjs(formState.value.timeInfo[1]).format('YYYY-MM-DD HH:mm:ss')
			:	null,
		content: formState.value.content,
		imageIds: formState.value.imageIds,
		provinceId:
			firstChange.value ?
				formState.value?.provinceId
			:	formState.value.location?.[0],
		cityId:
			firstChange.value ?
				formState.value?.cityId
			:	formState.value.location?.[1],
		districtId:
			firstChange.value ?
				formState.value?.districtId
			:	formState.value.location?.[2],
		payMoney: formState.value.payMoney,
		userId: formState.value.userId,
	};
	// 如果是新增，则有消费现金接口，否则直接走修改接口
	// if (method === 'post') {
	// 	// 消费现金接口
	// 	let currentParams = {
	// 		relatedBusinessInfo: JSON.stringify(params),
	// 		type: formState.value?.topFlag ? 'create_dating_top' : 'create_dating',
	// 		amount: formState.value.payMoney,
	// 		userId: formState.value.userId,
	// 		source: 'end',
	// 	};
	// 	const {
	// 		code,
	// 		data,
	// 		message: messageInfo,
	// 	} = await reduceMoneyInfo(currentParams)
	// 		.catch((error: any) => {
	// 			message.error(error?.message || '查询失败！');
	// 		})
	// 		.finally(() => {
	// 			loading.value = false;
	// 		});
	// 	console.log('reduceAmountInfo', code, data, messageInfo);
	// 	if (code == '200') {
	// 		message.success('创建约会成功，请到订单中进行审核！');
	// 		emit('handleOk', false);
	// 	} else {
	// 		message.error(messageInfo || '保存失败！');
	// 	}
	// } else {
	// 修改接口
	addOrEditDatingInfo(method, params)
		.then((res: any) => {
			if (res.code == '200') {
				message.success((res && res.message) || '保存成功！');
				formState.value = {};
				emit('handleOk', false);
			} else {
				message.error((res && res.message) || '保存失败！');
			}
		})
		.catch((error: any) => {
			message.error(error?.message || '查询失败！');
		})
		.finally(() => {
			loading.value = false;
		});
};

const onFinish = (values: any): void => {
	console.log('Success:', values);
};

const onFinishFailed = (errorInfo: any): void => {
	console.log('Failed:', errorInfo);
};

const customImageRequest = (file: any[]) => {
	if (file?.length) {
		formState.value.imageIds = file.map((item) => item.uid).join(',');
	} else {
		formState.value.imageIds = null;
	}
};

// 查询用户信息
const getUserInfoListInfo = async () => {
	let params = {};
	let res = await getUserInfoList(params);
	const { code, data, message: messageInfo } = res;
	if (code === '200') {
		userList.value = data;
	} else {
		userList.value = [];
		message.warn(messageInfo || '失败，请联系管理员！');
	}
};

const init = async (): Promise<void> => {
	getDictInfoList();
	getUserInfoListInfo();
	fileInfo.value = [];
	if (props.modelInfo) {
		if (props.modelInfo.id) {
			getDatingInfoDetail(props.modelInfo.id)
				.then((res) => {
					if (res.code == '200') {
						formState.value = res.data;
						modelConfig.confirmLoading = false;
						formState.value.location = [
							res.data?.provinceName,
							res.data?.cityName,
							res.data?.districtName,
						];
						firstChange.value = true;
						formState.value.timeInfo = [
							res.data?.startTime ? dayjs(res.data?.startTime) : null,
							res.data?.endTime ? dayjs(res.data?.endTime) : null,
						];
						if (formState.value?.fileInfoVoList?.length) {
							formState.value?.fileInfoVoList.forEach((item: any) => {
								fileInfo.value.push({
									id: item?.id,
									url: item?.preUrl || '',
								});
							});
						} else {
							fileInfo.value = [];
						}
					} else {
						message.error((res && res.message) || '查询失败！');
					}
				})
				.catch((error: any) => {
					message.error(error?.message || '查询失败！');
				});
		} else {
			modelConfig.confirmLoading = false;
			formState.value = {};
			fileInfo.value = [];
			firstChange.value = false;
		}
	}
	locationTree.value = await getLocationTreeInfo(0);
	locationTree.value.forEach((item) => {
		item.isLeaf = false;
		item.level = 1;
	});
};

const emit = defineEmits(['handleOk', 'handleCancel']);

watch(
	() => props.open,
	(newVal) => {
		modalOpen.value = newVal;
		if (newVal) {
			init();
		}
	},
	{
		immediate: true,
		deep: true,
	},
);

defineExpose({ handleOk, handleCancel });
</script>
<style lang="scss" scoped></style>
